package com.geping.etl.common.interceptor;

import com.geping.etl.common.entity.Sys_Subject;
import com.geping.etl.common.entity.Sys_UserAndOrgDepartment;
import com.geping.etl.common.exceptoin.NoAccessRuntimeException;
import com.geping.etl.common.security.authentication.AuthServiceContainer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/***
 *
 * 拦截器处理
 * @author liang.xu
 * @date 2021.8.5
 */
@Slf4j
public class AuthSafeURLInterceptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //日志添加
        String traceId = MDC.get("traceId");
        if(StringUtils.isBlank(traceId)){
            traceId = UUID.randomUUID().toString();
            traceId = traceId.replaceAll("-", "").toUpperCase();
            MDC.put("traceId", traceId);
        }

        String url = request.getRequestURI();//获取请求路径

        if(url.contains("swagger-resources/")
                ||url.contains("swagger-ui.html")
                ||url.contains("v2/")
                ||url.contains("webjars/")
                ||url.contains("/bx/")
                ||url.contains("/deleteRule")
                ||url.contains("/synPersonBankInfo")
                ||url.contains("/synLogs")
                ||url.contains("/getSys_Menu")){
            return true;
        }
        log.info("url = {}", url);
        if(isNotNeedAuthUrl(url)) {
            return csrfInterceptor(request, response, url);
        }
        Sys_UserAndOrgDepartment user = (Sys_UserAndOrgDepartment) request.getSession().getAttribute("sys_User");
        //如果用户未登录
        if(user == null){
                response.sendRedirect(request.getContextPath()+"/loginUi");
                return false;
        }
        if(isIndexRequest(request,url)){
            return true;
        }
        //鉴权处理
       boolean authResult=AuthServiceContainer.doAuth(request.getServletPath().replace("/",""),request);
       if(authResult){
           authResult=csrfInterceptor(request, response, url);
        }
       if(!authResult){
           throw new NoAccessRuntimeException("没有权限访问");
       }
       return authResult;
    }

    /**
     * 判断是否是index请求
     * @param request
     * @return
     */
    private boolean isIndexRequest(HttpServletRequest request,String url) {
        List<Sys_Subject> subjectList = (List<Sys_Subject>) request.getSession().getAttribute("subjectId");
        if (url.endsWith("index")) {
            Integer subjectId = Integer.parseInt(request.getParameter("subjectId"));
            for (Sys_Subject sys_subject : subjectList) {
                if (sys_subject.getId() == subjectId) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 开放的请求
     * @param url
     * @return
     */
    private boolean isNotNeedAuthUrl(String url) {
        return url.endsWith("/login") || url.endsWith("/loginUi");
    }

    public final static List<String> csrfUrl = Arrays.asList("findRecordBySubject","addGroupInfo","findReportBySubjectId","audit_authority","showLogsUi","role_distribution","getRole_Ui","sys_user","sys_org","sys_department","home","userOut","login","loginUi","userOut","getAllSys_Auth_Role","showLogs","deleteSys_Org","editPasswordSys_User","getSys_Menu","PETLRunUi","panelView","tableMarView","getSystemName","getNameId","DownloadLog","addMenu","checkPwd","dataCount","dataMarView");

    private boolean csrfInterceptor(HttpServletRequest request, HttpServletResponse response, String url){
        boolean flag = true;
        String endUrl = url.substring(url.lastIndexOf("/")+1);
        if(!csrfUrl.contains(endUrl)){
            if (StringUtils.isNotBlank(request.getParameter("randSession"))) {
                if (!request.getParameter("randSession").equals(request.getSession().getAttribute("authId"))) {
                    flag = false;
                }
            } else {
                flag = false;
            }
        }
        return flag;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        MDC.remove("traceId");
        MDC.remove("userId");
    }



    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub

    }
}